package com.zzyl.service.impl;

import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.entity.Member;
import com.zzyl.entity.UserLoginRequestDto;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

    private final MemberMapper memberMapper;

    private final WechatService wechatService;

    private final JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo loginCustomer(UserLoginRequestDto userLoginRequestDto) {
        //第一步，调用微信api，通过code获取用户的的openId
        String code = userLoginRequestDto.getCode();
        String openId = wechatService.getOpenId(code);

        //第二步，根据openid查询客户信息
        Member member = memberMapper.selectById(openId);

        //第三步，判断客户是否为空，如果为空，创建用户，并赋值openid
        if (ObjectUtil.isEmpty(member)){
            member = Member.builder().openId(openId).build();
        }

        //第四步，根据code获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());

        //第五步，判断该手机号与该用户保存的手机号是否相等，不相等就重新赋值
        if (ObjectUtil.notEqual(phone,member.getPhone())){
            member.setPhone(phone);
        }

        //第六步，判断该id是否存在，存在就更新数据，不存在就重新增加
        if (ObjectUtil.isEmpty(member.getId())){
            memberMapper.insert(member);
        }else {
            memberMapper.update(member);
        }
        //保存新的用户
        //随机组装昵称，词组+手机号后四位
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(member.getPhone(), 7);

        member.setName(nickName);

        //第七步，将用户id和昵称封装到jwt中返回，
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.JWT_USERID,member.getId());
        claim.put(Constants.JWT_USERNAME,member.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claim);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }
}
